import { API_BASE_URL } from '../config/apiConfig';

// 定义回调函数类型
export type SSEMessageCallback = (eventType: string, data: string) => void;
export type SSEErrorCallback = (error: Event) => void;
export type SSECompleteCallback = () => void;

// SSE 连接实例接口
export interface SSEConnection {
    close: () => void;
}

/**
 * 创建 Manus 智能体 SSE 连接
 * @param message 用户消息
 * @param onMessage 消息接收回调
 * @param onError 错误处理回调
 * @param onComplete 流完成回调
 * @returns 包含关闭方法的连接对象
 */
export function createManusSSEConnection(
    message: string,
    onMessage: SSEMessageCallback,
    onError: SSEErrorCallback,
    onComplete: SSECompleteCallback
): SSEConnection {
    // 创建 EventSource 实例
    const eventSource = new EventSource(`${API_BASE_URL}/ai/manus/chat/sse?message=${encodeURIComponent(message)}`, {
        withCredentials: true
    });

    // 监听所有自定义事件类型
    const eventTypes = ['thinking', 'action', 'result', 'error', 'finished', 'complete'];
    eventTypes.forEach(type => {
        eventSource.addEventListener(type, (event: MessageEvent) => {
            try {
                onMessage(type, event.data);
            } catch (error) {
                console.error('SSE 消息处理错误:', error);
            }
        });
    });

    // 错误处理
    eventSource.onerror = (error) => {
        // 检查连接状态，如果是正常关闭则不触发错误
        if (eventSource.readyState === EventSource.CLOSED) {
            console.log('SSE连接正常关闭');
            return;
        }

        onError(error);
        eventSource.close();
        onComplete();
    };

    // 监听连接关闭事件
    eventSource.addEventListener('complete', () => {
        eventSource.close();
        onComplete();
    });

    // 返回连接对象
    return {
        close: () => {
            if (eventSource.readyState !== EventSource.CLOSED) {
                eventSource.close();
                onComplete();
            }
        }
    };
}